<template>
  <div>
    <el-card class="box-card">
      <el-button type="primary" icon="Plus" @click="addTradmark">添加品牌</el-button>
      <el-table style="margin: 10px 0px" border :data="tademarkArr">
        <el-table-column label="序号" width="80px" type="index"></el-table-column>
        <el-table-column label="品牌名称" prop="tmName" align="center"></el-table-column>
        <el-table-column label="品牌LOGO" align="center">
          <template #default="scope">
            <img :src="scope.row.logoUrl" alt="" style="width: 100px; height: 100px" />
          </template>
        </el-table-column>
        <el-table-column label="品牌操作">
          <template #default="scope">
            <el-button type="warning" icon="Edit" @click="updataTrademark(scope.row)"></el-button>
            <el-popconfirm
              :title="`你确定删除${scope.row.tmName}`"
              width="250px"
              icon="Delete"
              @confirm="reomoveTradeMark(scope.row.id)"
            >
              <template #reference>
                <el-button type="danger" icon="Delete" />
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- //分页器 -->
      <el-pagination
        @current-change="getHasTademark"
        @size-change="sizeChange"
        :pager-count="9"
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="[3, 5, 7, 9]"
        :background="true"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
      />
    </el-card>
  </div>
  <!-- 对话框 -->
  <el-dialog v-model="dialogVisible" :title="trademarkParams.id ? '修改品牌' : '添加品牌'">
    <el-form
      style="width: 80%"
      label-width="100px"
      :rules="rules"
      ref="formRef"
      :model="trademarkParams"
    >
      <el-form-item label="品牌名称" prop="tmName">
        <el-input placeholder="请输入品牌名称" v-model="trademarkParams.tmName"></el-input>
      </el-form-item>
      <el-form-item label="品牌LOGO" prop="logoUrl">
        <el-upload
          class="avatar-uploader"
          action="/api2/admin/product/fileUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="trademarkParams.logoUrl" :src="trademarkParams.logoUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirm">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import type { UploadProps } from 'element-plus'
import { ElMessage } from 'element-plus'
import {
  reqHasTrademark,
  reqAddOrUpdateTrademark,
  reqDeleteTrademark,
} from '@/api/product/trademark'
import { ref, onMounted, reactive, nextTick } from 'vue'
import type { Records, TrandeMarkResponseData, TradeMark } from '@/api/product/trademark/type'
const pageNo = ref<number>(1)
const limit = ref<number>(5)
//后端返回的数据总条数
const total = ref<number>(0)
const tademarkArr = ref<Records>([])
//控制对话框的出现和消失
const dialogVisible = ref<boolean>(false)
const trademarkParams = reactive<TradeMark>({
  tmName: '',
  logoUrl: '',
})
//获取表单对象
const formRef = ref()
const getHasTademark = async (page = 1) => {
  pageNo.value = page
  const result: TrandeMarkResponseData = await reqHasTrademark(pageNo.value, limit.value)
  if (result.code == 200) {
    total.value = result.data.total
    tademarkArr.value = result.data.records
  }
  // console.log(result);
}
onMounted(() => {
  getHasTademark()
})
//页面大小发现变化
const sizeChange = (value: any) => {
  limit.value = value
  getHasTademark()
}
//点击添加按钮触发的函数
const addTradmark = () => {
  trademarkParams.id = 0
  trademarkParams.tmName = ''
  trademarkParams.logoUrl = ''
  dialogVisible.value = true
  //清除错误验证信息
  nextTick(() => {
    formRef.value.clearValidate()
  })
}
//上传图片组件->上传图片之前触发的钩子函数
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile: any) => {
  //钩子是在图片上传成功之前触发,上传文件之前可以约束文件类型与大小
  //要求:上传文件格式png|jpg|gif 4M
  if (rawFile.type == 'image/png' || rawFile.type == 'image/jpeg' || rawFile.type == 'image/gif') {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '上传文件大小小于4M',
      })
      return false
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传文件格式务必PNG|JPG|GIF',
    })
    return false
  }
}
//图片上传成功钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  //response:即为当前这次上传图片post请求服务器返回的数据
  //收集上传图片的地址,添加一个新的品牌的时候带给服务器
  trademarkParams.logoUrl = response.data
  //图片上传成功,清除掉对应图片校验结果
  formRef.value.clearValidate()
}
//点击确认触发的函数
const confirm = async () => {
  await formRef.value.validate()
  const result: any = await reqAddOrUpdateTrademark(trademarkParams)
  if (result.code == 200) {
    dialogVisible.value = false
    //添加或者修改品牌
    ElMessage({
      type: 'success',
      message: trademarkParams.id ? '修改品牌成功' : '添加品牌成功',
    })
    getHasTademark(trademarkParams.id ? pageNo.value : 1)
  } else {
    dialogVisible.value = false
    ElMessage({
      type: 'success',
      message: trademarkParams.id ? '修改品牌失败' : '添加品牌失败',
    })
  }
}
//点击修改触发的按钮
const updataTrademark = (row: TradeMark) => {
  Object.assign(trademarkParams, row)
  dialogVisible.value = true
  //清除错误验证信息
  //清除错误验证信息
  nextTick(() => {
    formRef.value.clearValidate()
  })
}
//校验品牌名称
const validatortmName = (rule: any, value: any, callback: any) => {
  console.log(value)

  if (value.trim().length >= 2) {
    callback()
  } else {
    callback(new Error('品牌名称位数大于两位'))
  }
}
//校验品牌LOGO
const validatorLogoUrl = (rule: any, value: any, callback: any) => {
  if (value) {
    callback()
  } else {
    callback(new Error('LOGO图片务必上传'))
  }
}
const rules = {
  tmName: [{ required: true, trigger: 'blur', validator: validatortmName }],
  logoUrl: [{ required: true, trigger: 'blur', validator: validatorLogoUrl }],
}
//删除
const reomoveTradeMark = async (id: number) => {
  const result: any = await reqDeleteTrademark(id)
  console.log(result)

  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    getHasTademark(tademarkArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
  } else {
    ElMessage({
      type: 'success',
      message: '删除失败',
    })
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
